package com.example.simpleforum.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 登录检查过滤器
 * 用于检查用户是否已登录，未登录则重定向到登录页面
 */
public class LoginCheckFilter implements Filter {
    private List<String> excludedUrls;
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 获取排除的URL列表（不需要登录就能访问的URL）
        String excludedUrlsParam = filterConfig.getInitParameter("excludedUrls");
        if (excludedUrlsParam != null) {
            excludedUrls = Arrays.asList(excludedUrlsParam.split(","));
        }
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        
        // 获取请求的URI
        String requestURI = req.getRequestURI();
        String contextPath = req.getContextPath();
        String path = requestURI.substring(contextPath.length());
        
        // 检查是否是排除的URL
        boolean isExcluded = false;
        if (excludedUrls != null) {
            for (String excludedUrl : excludedUrls) {
                if (path.startsWith(excludedUrl.trim())) {
                    isExcluded = true;
                    break;
                }
            }
        }
        
        // 如果是排除的URL，或者用户已登录，则继续执行
        HttpSession session = req.getSession();
        if (isExcluded || session.getAttribute("user") != null) {
            chain.doFilter(request, response);
        } else {
            // 未登录，重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        }
    }
    
    @Override
    public void destroy() {
        // 清理资源
        excludedUrls = null;
    }
}